﻿using DAL;
using DBUtility;
using Model;
using System;
using System.Collections.Generic;

namespace BLL.BatchBLL
{
    public class createBatchBLL
    {
        private WorkOrderRepository workOrderRepository = new WorkOrderRepository();
        private BatchRepository batchRepository = new BatchRepository();
        private ProductRepository productRepository = new ProductRepository(); // 添加产品仓库

        // 查询所有工单信息
        public List<WorkOrder> GetAllWorkOrder()
        {
            return workOrderRepository.GetAllWorkOrders();
        }

        // 获取最大的批次号
        public int GetMaxBatchId()
        {
            string sql = "SELECT MAX(BatchId) FROM Batch";
            var result = DBHelper.ExecuteScalar(sql);
            if (result != null && result != DBNull.Value)
            {
                return Convert.ToInt32(result);
            }
            else
            {
                return 0;
            }
        }

        // 创建批次
        public bool CreateBatch(int workOrderId, int quantity, out Batch createdBatch)
        {
            try
            {
                int newBatchId = GetMaxBatchId() + 1;
                createdBatch = new Batch
                {
                    BatchId = newBatchId,
                    WorkOrderId = workOrderId,
                    Quantity = quantity,
                    SubQuantity = quantity,
                    GoodQuantity = 0,
                    NGQuantity = 0,
                    Unit = "PC",
                    LockStatus = "未锁定",
                    EventName = "Create Batch",
                    EventUser = "System",
                    EventTime = DateTime.Now,
                    EventRemarks = "Batch created by system"
                };

                batchRepository.AddBatch(createdBatch);
                return true;
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"创建批次失败: {ex.Message}");
                createdBatch = null;
                return false;
            }
        }

        // 根据工单号查询单个工单
        public WorkOrder GetWorkOrderById(int workOrderId)
        {
            return workOrderRepository.GetWorkOrderById(workOrderId);
        }

        // 保存批次信息
        public void SaveBatch(Batch batch)
        {
            batchRepository.AddBatch(batch);
        }

        // 新增：通过工单号获取产品信息
        public Product GetProductByWorkOrderId(int workOrderId)
        {
            var workOrder = workOrderRepository.GetWorkOrderById(workOrderId);
            if (workOrder != null)
            {
                return productRepository.GetProductById(workOrder.ProductId);
            }
            return null;
        }
    }
}